////////////////////////////////////////////////////////////// //Count the number of times a phrase is found in a phrase ///////////////////////////////////////////////////////////// #include using namespace std; void main() { char phrase[10000]; char searchPhrase[100]; char replacePhrase[100]; cout << "Enter phrase> "; cin.getline(phrase,10000); cout << "Enter word to search for> "; cin.getline(searchPhrase,100); //strchr - searches for a char in a string //strtok - tokenizes a string //strstr - searches for a string in a string int timesFound = 0; //this is the apple the worm was eating in the tree char* p = strstr(phrase, searchPhrase); while(p != NULL) { timesFound++; p = strstr(p + 1, searchPhrase); } cout << searchPhrase << " was found in the phrase "; cout << timesFound << " times.\n"; } ////////////////////////////////////////////////////////////// //Search and replace example ///////////////////////////////////////////////////////////// #include using namespace std; //searching //search and replace void main() { char phrase[10000]; char searchPhrase[100]; char replacePhrase[100]; cout << "Enter phrase> "; cin.getline(phrase,10000); cout << "Enter word to search for> "; cin.getline(searchPhrase,100); cout << "Enter word to replace with> "; cin.getline(replacePhrase,100); //this is the apple the worm was eating in the tree //this is candy apple candy worm was eating in candy tree //this is a apple a worm was eating in a tree char* pStart = phrase; char* pFound = strstr(phrase, searchPhrase); char answer[10000] = ""; while(pFound != NULL) { int charactersToCopy = int(pFound - pStart); strncat(answer, pStart, charactersToCopy); strcat(answer, replacePhrase); pStart = pFound + strlen(searchPhrase); pFound = strstr(pStart, searchPhrase); } strcat(answer,pStart); strcpy(phrase,answer); cout << "The phrase is now = \n"; cout << phrase << endl; }